﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sinacor.Infra.Tools.ServiceRegistration.Business
{
    public class SubModule
    {
        #region Attributes

        private Data.SubModule _resourceAccess;
        private object locker = new object();

        #endregion

        #region Constructor

        public SubModule()
        {
            this._resourceAccess = new Data.SubModule();
        }

        #endregion

        #region Methods

        public List<Entity.SubModule> SelectSubModule(Entity.SubModule entity)
        {
            return _resourceAccess.SelectSubModule(entity);
        }

        public Entity.SubModule PersistSubModule(Entity.SubModule entity)
        {
            Entity.SubModule subModule = new Entity.SubModule() { SubModuleName = entity.SubModuleName, Module = entity.Module };
            List<Entity.SubModule> subModules = null;

            subModules = _resourceAccess.SelectSubModule(subModule);

            if (subModules.Count == 0)
            {
                subModule = InsertSubModule(entity);
            }
            else
            {
                subModule = subModules[0];

                subModule.DateChange = entity.DateChange;
                subModule.DataOrigin = entity.DataOrigin;
                UpdateSubModule(subModule);
            }

            return subModule;
        }

        public Entity.SubModule InsertSubModule(Entity.SubModule entity)
        {
            entity.SubModuleId = this.GetNextSubModuleId();
            return _resourceAccess.InsertSubModule(entity);
        }

        public void UpdateSubModule(Entity.SubModule entity)
        {
            _resourceAccess.UpdateSubModule(entity);
        }

        public void DeleteSubModule(Entity.SubModule entity)
        {
            _resourceAccess.DeleteSubModule(entity);
        }

        public int GetNextSubModuleId()
        {
            int nextId = 0;

            lock (locker)
            {
                nextId = _resourceAccess.GetNextSubModuleId();
            }

            return nextId;
        }

        public int GetNextSubModulePort()
        {
            int nextPort = 0;

            lock (locker)
            {
                nextPort = _resourceAccess.GetNextSubModulePort();
            }

            return nextPort;
        }

        #endregion
    }
}
